package com.linkage.user.service;
import java.util.List;
//import java.awt.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.linkage.user.pojo.User;


@Service
public class LoginService {
    @Autowired
    private UserService userService;

    public boolean login(HttpServletRequest request, String userName, String password) {
        if (StringUtils.isEmpty(userName)) {
            return false;
        }
        String sessionCode =(String) request.getSession().getAttribute("session_vcode");
        String paramCode = request.getParameter("verifycode");
        System.out.println("sessionCode"+"paramCode");
        User user = this.userService.loadByLoginName(userName);
        if (user != null && password.equals(user.getPassword())&&sessionCode.equalsIgnoreCase(paramCode)) {
            storeInSession(request.getSession(), "LOGIN_USER_KEY_IN_SESSION", user);
            return true;
        }

        return false;
    }

    public boolean logout(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute("LOGIN_USER_KEY_IN_SESSION");
        if (obj == null || !(obj instanceof User))
            return false;

        request.getSession().removeAttribute("LOGIN_USER_KEY_IN_SESSION");
        return true;
    }

    private void storeInSession(HttpSession session, String key, Object object) {
        session.setAttribute(key, object);
    }
    
    public void register(User user, HttpServletRequest request) {

		// TODO Auto-generated method stub
		this.userService.registOne(user);
	}
    
    public boolean checkRegister(String userName,String password, User user, HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<User> users=this.userService.queryAll();
		for (User user1 : users) {
			if (user1.getUserName().equals(userName)) {
				return false;
			}
		}
		return true;
	}
    
    
}
